//
//  TableViewDataSource.m
//  clh
//
//  Created by 曹连华 on 2018/4/11.
//  Copyright © 2018年 曹连华. All rights reserved.
//

#import "LVTableViewDataSource.h"
#import "LVBaseTableViewTVCell.h"

#define WEAK_SELF __weak typeof(self)weakSelf = self
#define STRONG_SELF __strong typeof(weakSelf)self = weakSelf

@interface LVTableViewDataSource ()

@property (nonatomic, weak) id <UITableViewDataSource> tableViewDataSource;

@end

@implementation LVTableViewDataSource

- (void)resetDataSource:(id<UITableViewDataSource>)dataSource {
    self.tableViewDataSource = dataSource;
}


#pragma mark - TableView - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if(self.tableViewDataSource && [self.tableViewDataSource respondsToSelector:@selector(numberOfSectionsInTableView:)]) {
        return [self.tableViewDataSource numberOfSectionsInTableView:tableView];
    }
    return self.sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(self.tableViewDataSource && [self.tableViewDataSource respondsToSelector:@selector(tableView:numberOfRowsInSection:)]){
        return [self.tableViewDataSource tableView:tableView numberOfRowsInSection:section];
    }
    return [self sectionModelAtIndex:section].rows.count;
}

- (LVBaseTableViewTVCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LVBaseCellRowModel *rowModel = [self rowModelAtIndex:indexPath];
    
    if (self.tableViewDataSource && [self.tableViewDataSource respondsToSelector:@selector(tableView:cellForRowAtIndexPath:)]) {
        return (LVBaseTableViewTVCell *)[self.tableViewDataSource tableView:tableView cellForRowAtIndexPath:indexPath];
    }
    
    LVBaseTableViewTVCell * cell = (LVBaseTableViewTVCell *)[tableView dequeueReusableCellWithIdentifier:rowModel.reuseIdentifier];
    if (cell == nil) {
        if (rowModel.loadType == TVCCellLoadXIB) {
            [tableView registerNib:[UINib nibWithNibName:rowModel.reuseIdentifier bundle:nil] forCellReuseIdentifier:rowModel.reuseIdentifier];
            cell = (LVBaseTableViewTVCell *)[rowModel createTVCCellByXIB];
            
        } else {
            cell = (LVBaseTableViewTVCell *)[rowModel createTVCCellByCode];
        }
    }
    if ([cell respondsToSelector:@selector(updateTVCCellWithRowModel:atIndexPath:)]) {
        [cell updateTVCCellWithRowModel:rowModel atIndexPath:indexPath];
    }
    
    
    return cell;
}

- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if(self.tableViewDataSource && [self.tableViewDataSource respondsToSelector:@selector(tableView:viewForHeaderInSection:)]) {
        return nil;
    } else if(self.tableViewDataSource && [self.tableViewDataSource respondsToSelector:@selector(tableView:titleForHeaderInSection:)]) {
        return [self.tableViewDataSource tableView:tableView titleForHeaderInSection:section];
    }
    return [self sectionModelAtIndex:section].sectionHeader.headerFooterTitle;
}

- (nullable NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    if(self.tableViewDataSource && [self.tableViewDataSource respondsToSelector:@selector(tableView:viewForFooterInSection:)]) {
        return nil;
    } else if(self.tableViewDataSource && [self.tableViewDataSource respondsToSelector:@selector(tableView:titleForFooterInSection:)]) {
        return [self.tableViewDataSource tableView:tableView titleForFooterInSection:section];
    }
    return [self sectionModelAtIndex:section].sectionFooter.headerFooterTitle;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if(self.tableViewDataSource && [self.tableViewDataSource respondsToSelector:@selector(tableView:canEditRowAtIndexPath:)]) {
        return [self.tableViewDataSource tableView:tableView canEditRowAtIndexPath:indexPath];
    }
    return [self rowModelAtIndex:indexPath].canEdit;
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    if(self.tableViewDataSource && [self.tableViewDataSource respondsToSelector:@selector(tableView:canMoveRowAtIndexPath:)]) {
        return [self.tableViewDataSource tableView:tableView canMoveRowAtIndexPath:indexPath];
    }
    return [self rowModelAtIndex:indexPath].canMove;
}

- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if(self.tableViewDataSource && [self.tableViewDataSource respondsToSelector:@selector(sectionIndexTitlesForTableView:)]) {
        self.sectionIndexTitles = [self.tableViewDataSource sectionIndexTitlesForTableView:tableView];
    }
    return self.sectionIndexTitles;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    if(self.tableViewDataSource && [self.tableViewDataSource respondsToSelector:@selector(tableView:sectionForSectionIndexTitle:atIndex:)]) {
        return [self.tableViewDataSource tableView:tableView sectionForSectionIndexTitle:title atIndex:index];
    } else if(self.sectionIndexTitles.count > 0) {
        return [self.sectionIndexTitles indexOfObject:title];
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if(self.tableViewDataSource && [self.tableViewDataSource respondsToSelector:@selector(tableView:commitEditingStyle:forRowAtIndexPath:)]) {
        [self.tableViewDataSource tableView:tableView commitEditingStyle:editingStyle forRowAtIndexPath:indexPath];
    } else {
        
        LVBaseCellRowModel *rowModel = [self rowModelAtIndex:indexPath];
        
        if (rowModel.editingStyle == UITableViewCellEditingStyleDelete) {//删除数据
            if (self.removeRowModelBlock) {
                WEAK_SELF;
                self.removeRowModelBlock(^(BOOL operateSuccess) {
                    if (operateSuccess) {
                        STRONG_SELF;
                        [self removeRowModel:rowModel];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [tableView beginUpdates];
                            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:rowModel.editingAnimationStyle];
                            [tableView endUpdates];
                        });
                    }
                },  indexPath);
            }
            
        } else if (rowModel.editingStyle == UITableViewCellEditingStyleInsert) {//插入数据
            if (self.insertRowModelBlock) {
                WEAK_SELF;
                self.insertRowModelBlock(^(BOOL operateSuccess) {
                    if (operateSuccess) {
                        STRONG_SELF;
                        [self insertRowModel:rowModel atIndex:indexPath];
                        
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [tableView beginUpdates];
                            [tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:rowModel.editingAnimationStyle];
                            [tableView endUpdates];
                        });
                    }
                },  indexPath);
            }
        }
    }

}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    if(self.tableViewDataSource && [self.tableViewDataSource respondsToSelector:@selector(tableView:moveRowAtIndexPath:toIndexPath:)]) {
        [self.tableViewDataSource tableView:tableView moveRowAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath];
    } else {
        LVBaseCellRowModel *sourceRow = [self rowModelAtIndex:sourceIndexPath];
        
        LVBaseCellSectionModel *sourceSectionModel = [self sectionModelAtIndex:sourceIndexPath.section];
        LVBaseCellSectionModel *destinationSectionModel = [self sectionModelAtIndex:destinationIndexPath.section];
        
        if (self.moveRowModelBlock) {
            self.moveRowModelBlock(^(BOOL operateSuccess) {
                if (operateSuccess) {
                    
                    [sourceSectionModel.rows removeObjectAtIndex:sourceIndexPath.row];//先把原来位置的 rowModel 删除
                   
                    if (sourceIndexPath.section == destinationIndexPath.section) {//同组 移动
                        [sourceSectionModel.rows insertObject:sourceRow atIndex:destinationIndexPath.row];
                    } else {// 不同组移动
                        [destinationSectionModel.rows insertObject:sourceRow atIndex:destinationIndexPath.row];
                    }
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [tableView reloadSections:[NSIndexSet indexSetWithIndex:sourceIndexPath.section] withRowAnimation:UITableViewRowAnimationNone];
                    });
                }
            }, sourceIndexPath, destinationIndexPath);
        }
    }
}
@end
